package com.abc.robot01.flutter


import android.os.Bundle
import android.util.Log
import androidx.annotation.NonNull
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.activity.HuXingShuJuActivity
import com.abc.robot01.activity.HuXingShuJuActivityByPhone
import com.abc.robot01.activity.HuXingTiaoZheng
import com.abc.robot01.activity.HuXingXuanZheActivity
import com.abc.robot01.activity.startActivity
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.vivemodel.Robot
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.KeyData
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject


class HuXingXuanZheActivity : FlutterActivity() {

    companion object {
        const val TAG="HuXingXuanZheActivity"
        const val CHANNEL: String = "com.abc.robot01.flutter.huxingxuanze"
    }

    lateinit var designPackageId: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        designPackageId = intent.getStringExtra("designPackageId")!!
//        designPackageId = "123"
    }


    override fun onResume() {
        super.onResume()
        // 通知 Dart 层
        MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger,CHANNEL)
            .invokeMethod("onResume", null)
    }


    override fun getInitialRoute(): String {
        // 指定加载的 Flutter 界面
        return "/huxingxuanze"
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),CHANNEL)
            .setMethodCallHandler { call, result ->

                if (call.method!!.contentEquals("init")) {
                    result.success(Robot.accessToken+"_"+Robot.userId+"_"+Robot.companyId)
                    return@setMethodCallHandler
                }

                if (call.method!!.contentEquals("search_by_phone")) {
                    startActivity<HuXingShuJuActivityByPhone>() {
                        val phone = call.argument<String>("phone")
                        putExtra("phone", phone)
                        putExtra("designPackageId", designPackageId)
                    }
                    result.success(true)
                    return@setMethodCallHandler
                }
                if (call.method!!.contentEquals("start_HuXingShuJuActivity")) {
                    val housePlansId = call.argument<String>("housePlansId")
                    startActivity<HuXingShuJuActivity>() {
                        putExtra("housePlansId", housePlansId)
                        putExtra("designPackageId", designPackageId)
                    }
                    result.success(true)
                    return@setMethodCallHandler
                }

                if (call.method!!.contentEquals("start_HuXingTiaoZheng")) {
                        val housePlansId = call.argument<String>("housePlansId")
                        val thumbnail = call.argument<String>("thumbnail")
                    Log.e(TAG,"housePlansId:"+housePlansId);
                    Log.e(TAG,"thumbnail:"+thumbnail);

                    lifecycleScope.launch {
                        val res = RetrofitService.instance.saveReadingTask(
                            accessToken = Robot.accessToken,
                            userId = Robot.userId,
                            companyId = Robot.companyId,
                            housePlansId = housePlansId!!,
                            designPackageId = designPackageId,
                            fileUrl = thumbnail!!,
                        )
                        Log.e(HuXingXuanZheActivity.TAG, "户型识别结果:" + res.code)
                        val code = res.code
                        if (code == 200
                        ) {
                            Log.e(TAG, "户型识别结果:" + res.data)
                            while (true) {
                                delay(1000)
                                val a = RetrofitService.instance
                                    .getTaskStatus(
                                        accessToken = Robot.accessToken,
                                        userId = Robot.userId,
                                        companyId = Robot.companyId,
                                        taskId = res.data
                                    )
                                    .string()

                                Log.e(HuXingXuanZheActivity.TAG, "户型识别结果 轮询获取图片识别数据:" + a)

                                val status = JSONObject(a)
                                    .getJSONObject("data")
                                    .getString("status")
                                if (status == "2") {
                                    Log.e(TAG, "户型识别 成功:")
                                    val housePlansId2 =
                                        JSONObject(a)
                                            .getJSONObject("data")
                                            .getString("housePlansId")

                                    startActivity<HuXingTiaoZheng>() {
                                        putExtra("housePlansId", "" + housePlansId2)
                                        putExtra(
                                            "designPackageId",
                                            "" + designPackageId
                                        )
                                    }
                                    break
                                }
                            }
                        }
                        result.success(true)
                    }
                    return@setMethodCallHandler
                }


//                void onClick2() async {
//                    if(enable2){
//                        final bool result = await platformMethodChannel.invokeMethod(
//                                'start_HuXingTiaoZheng',
//                        {
//                            'housePlansId': _list[selectedIndex].id,
//                            'thumbnail': _list[selectedIndex].thumbnail,
//                        },
//                        );
//                    }
//                }





                if (call.method!!.contentEquals("get_points")) {
                    val mapName = call.argument<String>("name")
                    result.success("前台${mapName}_办公室${mapName}_办公室${mapName}")
                    return@setMethodCallHandler
                }
            }
    }


}
